<template>
  <div class="box">
    <el-row class="bottom-border">
      <!-- <el-col :span="24"> -->
      <!-- <div class="header"> -->
      <el-form ref="form" :model="form" label-width="100px">
        <el-row>
          <el-col :span="12" :md="6">
            <div class="waybill_list">
              <el-select v-model="form.codeType" clearable placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  @click.native="waybillTap(item.value)"
                />
              </el-select>
              <el-input
                v-model="form.code"
                clearable
                placeholder="最多输入30条"
              />
            </div>
          </el-col>
          <el-col :span="12" :md="6">
            <el-form-item label="网点名称">
              <networkSelect
                :selected-network="form.networkNameId"
                @select="handleSelect"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24" :md="12">
            <el-form-item label="查询时间">
              <el-date-picker
                v-model="form.value1"
                style="width: 100%"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" :md="6">
            <el-form-item label="考核状态">
              <el-select
                v-model="form.examineStatus"
                style="width: 100%"
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in assess"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :md="6">
            <el-form-item label="统计维度" clearable>
              <el-select
                v-model="form.collectType"
                clearable
                placeholder="请选择统计维度"
                style="width: 100%"
              >
                <el-option label="按网点统计" :value="1" />
                <el-option label="按承包区统计" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" :md="12" class="block" style="margin-bottom: 20px">
            <el-button type="primary" @click="onSubmit">查询</el-button>
            <el-button @click="reset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
      <!-- </div> -->
      <!-- </el-col> -->
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-button
          icon="el-icon-upload2"
          :disabled="tableData.length == 0"
          @click="exportTable"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-row>
      <el-table
        v-if="tableData.length !== 0"
        id="table2"
        :data="tableData"
        style="width: 100%"
        :border="true"
      >
        <el-table-column label="序号" type="index" />
        <template v-for="(column, index) in tableColumns">
          <el-table-column
            :key="index"
            :prop="column[0].fields"
            :label="column.length > 1 ? column[0].title1 : column[0].translate"
            :width="
              setWidth(
                column.length > 1 ? column[0].title1 : column[0].translate
              )
            "
            align="center"
            :fixed="
              column[0].fields == 'totalNum' ||
                column[0].fields == 'totalAmount'
                ? 'right'
                : false
            "
          >
            <template slot="header">
              {{ column.length > 1 ? column[0].title1 : column[0].translate }}
              <el-tooltip
                v-if="
                  column[0].fields !== 'networkName' &&
                    column[0].fields !== 'contractAreaName' &&
                    column[0].fields !== 'totalNum' &&
                    column[0].fields !== 'totalAmount'
                "
                class="item"
                effect="dark"
                :content="
                  column.length > 1 ? column[0].title1 : column[0].translate
                "
              >
                <i class="el-icon-question" />
              </el-tooltip>
            </template>
            <template slot-scope="scope">
              <span :class="column[0].fields == 'totalNum' ? 'percent' : ''">{{
                scope.row[column[0].fields]
              }}</span>
            </template>
            <template v-if="column.length > 1">
              <el-table-column
                :width="setWidth(column[0].title2)"
                :prop="column[0].fields"
                :label="column[0].title2"
                align="center"
              >
                <template slot-scope="scope">
                  <span class="percent">{{ scope.row[column[0].fields] }}</span>
                </template>
              </el-table-column>
              <el-table-column
                :width="setWidth(column[0].title2)"
                :prop="column[1].fields"
                :label="column[1].title2"
                align="center"
              />
            </template>
          </el-table-column>
        </template>
        <!-- <el-table-column width="200" label="操作" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button>编辑</el-button>
            <el-button>删除</el-button>
          </template>
        </el-table-column>-->
      </el-table>
    </el-row>
    <div class="block" style="display: flex; justify-content: flex-end">
      <el-pagination
        :current-page="form.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageDate.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="sizeChange"
        @current-change="currentChange"
      />
    </div>
  </div>
</template>
<script>
let that = ''
import networkSelect from '@/components/menuComponent/NetworkSelect.vue'
import { CustomerOrderAjax } from '@/api/customer'
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {
  components: {
    networkSelect
  },
  data() {
    return {
      // 运单号
      options: [
        {
          label: '运单号',
          value: 1
        },
        {
          label: '工单号',
          value: 2
        }
      ],
      assess: [
        {
          label: '全部',
          value: 1
        },
        {
          label: '已撤销',
          value: 2
        },
        {
          label: '未撤销',
          value: 3
        }
      ],
      form: {
        codeType: '', // 运单号、工单号
        code: '', // 单号
        collectType: '',
        networkNameId: '', // 网点名称ID
        currentPage: 1,
        examineStatus: '', // 考核状态
        value1: []
      },
      tableData: [],
      tableColumns: [],
      current: 1, // 当前页
      pages: 0, // 总页数
      total: 0, // 总条数
      pageDate: {
        pageNum: 1,
        pageSize: 10
      }
    }
  },
  created() {
    that = this
    that.getAjax()
  },
  methods: {
    exportTable() {
      var xlsxParam = { raw: true }
      var wb = XLSX.utils.table_to_book(
        document.querySelector('#table2'),
        xlsxParam
      )
      var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: 'application/octet-stream' }),
          '客诉工单账单-' + '.xlsx'
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
    },
    // 运单号和工单号切换部分
    waybillTap(e) {
      that.form.codeType = e
      that.form.code = ''
    },
    // 选择网点
    handleSelect(val) {
      this.form.networkNameId = val
    },
    reset() {
      that.pageDate.pageNum = 1
      that.form = {
        codeType: '', // 运单号、工单号
        code: '', // 单号
        collectType: '',
        networkNameId: '', // 网点名称ID
        currentPage: 1,
        examineStatus: '', // 考核状态
        value1: []
      }
      that.getAjax()
    },
    onSubmit() {
      that.getAjax()
    },
    sizeChange(e) {
      console.log(e)
      that.pageDate.pageSize = e
      that.getAjax()
    },
    currentChange(e) {
      console.log(e)
      that.pageDate.pageNum = e
      that.getAjax()
    },
    // 获取列表数据
    getAjax() {
      let startTime
      let endTime
      // console.log(that.form.value1)
      if (that.form.value1.length !== 0) {
        startTime = that.form.value1[0]
        endTime = that.form.value1[1]
      }
      const data = {
        codeType: that.form.codeType,
        code: that.form.code,
        networkNameId: that.form.networkNameId,
        examineStatus: that.form.examineStatus,
        collectType: that.form.collectType,
        startTime: startTime,
        endTime: endTime,
        pageDate: that.pageDate
      }
      // 去除无效字段
      for (const i in data) {
        if (!data[i]) delete data[i]
      }
      CustomerOrderAjax(data).then((res) => {
        if (res.code === 200) {
          const col = that.transformFields(res.data.fields)
          console.log('转换后的列:', col)
          that.tableColumns = col
          that.tableData = res.data.list.data
          that.current = res.data.list.current
          that.pages = res.data.list.pages
          that.total = res.data.list.total
          // that.tableColumns.push({ fields: 'operate', translate: '操作' })
        } else {
          that.resetTable()
        }
      })
      // .catch(err){

      // }
    },
    resetTable() {
      // that.tableColumns = [];
      that.tableData = []
      that.current = 1
      that.pages = 0
      that.total = 0
    },
    // 转换表格列格式以方便制作合并表头
    transformFields(data) {
      const grouped = {}
      data.forEach((obj) => {
        const { fields, translate } = obj
        let prefix = ''
        if (
          fields !== 'networkName' &&
          fields !== 'contractAreaName' &&
          fields !== 'totalNum' &&
          fields !== 'totalAmount'
        ) {
          if (fields.endsWith('Num')) {
            prefix = fields.split('Num')[0]
            obj.type = 'Num'
            obj.title1 = translate.split('数量')[0]
            obj.title2 = '数量'
          } else {
            prefix = fields.split('Amount')[0]
            obj.type = 'Amount'
            obj.title1 = translate.split('Amount')[0]
            obj.title2 = '金额'
          }
        } else {
          prefix = fields
        }
        if (!grouped[prefix]) {
          grouped[prefix] = []
        }
        grouped[prefix].push(obj)
      })
      const arr = Object.keys(grouped).map((key) => grouped[key])
      return arr
    },
    setWidth(e) {
      return 80 + e.length * 15
    }
  }
}
</script>
<style lang="scss" scoped>
.box {
  padding: 0px 20px;
}

.bottom-border {
  margin-top: 20px;
  border-bottom: 1px solid #d8d8d8;
}

.flex {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
}

.liLittle {
  border: 1px solid #9999;
  height: 150px;
  display: flex;
  flex-flow: column;
  justify-content: space-around;
}

.liLittle > span {
  font-size: 24px;
}

.f-row {
  display: flex;
  flex-flow: row;
  justify-content: space-around;
}

.littbox {
  display: flex;
  flex-flow: column;
  justify-content: space-around;
  height: 100px;
}

.flex-bettom {
  display: flex;
  justify-content: space-between;
}
.flex-center {
  display: flex;
  justify-content: center;
}
.header {
  padding: 20px 0;
  border-bottom: 1px solid #ccc;
}

.el-row {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.el-col {
  border-radius: 4px;
}

.waybill_list {
  display: flex;
  .el-select {
    width: 100px;
    padding-right: 10px;
  }
  .el-input {
    width: calc(100% - 100px);
    // padding: 0px 35px;
  }
}

.assess_list {
  .el-form-item__label {
    width: 118px !important;
  }
}
.block {
  display: flex;
  justify-content: flex-end;
}
.percent {
  color: #409eff;
}
// .el-form-item__content{
// 	margin-left: 0rpx !important;
// }
</style>
